<!-- 商家销量统计的横向柱状图 -->
<template>
  <div class="com-container">
      <div class="com-chart" ref="trend_ref" ></div>
      <div class="title">
        <span :style="comStyle">{{'┃ ' + showTitleType }}</span>
        <span :style="comStyle" class="iconfont title-icon" @click="showChoice = !showChoice">&#xe6eb;</span>
        <div class="select-con" v-show="showChoice"  :style="marginStyle" >
          <div class="select-item" v-for="item in allData.type" :key="item.key" @click="choiceTitleType(item.key)">{{item.text}}</div>
        </div>
      </div>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import { getThemeValue } from '@/utils/theme_utils'
export default {
  data () {
    return {
      chartInstance: null,
      allData: [], // 从服务器中获取的所有数据
      currentKey: 'map',
      showChoice: false,
      titleFontSize: 16
    }
  },
  created () { // 组件创建后 - 函数
    // 组件创建时，注册socket的回调函数
    this.$socket.registerCallBack('trendData', this.getData)
  },
  mounted () { // 组件挂载后 - 函数
    this.initChart()
    // this.getData()
    // 发送数据给服务器，告诉服务器，这个客户端需要数据
    this.$socket.send({
      action: 'getData',
      socketType: 'trendData',
      chartName: 'trend',
      value: ''
    })
    this.resizeChart()
    window.addEventListener('resize', this.resizeChart)
  },
  destroyed () { // 组件销毁时 - 函数
    // 组件销毁时移除监听器
    window.removeEventListener('resize', this.resizeChart)
    // 组件销毁时，注销socket的回调函数
    this.$socket.unregisterCallBack('trendData')
  },
  computed: {
    showTitleType () {
      if (this.allData) {
        return this.allData[this.currentKey].title
      }
      return ''
    },
    comStyle () {
      return {
        fontSize: this.titleFontSize + 'px',
        color: getThemeValue(this.theme).titleColor,
        backgroundColor: this.theme === 'chalk' ? '#222733' : '#fff'
      }
    },
    marginStyle () {
      return {
        fontSize: this.titleFontSize + 'px',
        marginLeft: this.titleFontSize + 'px',
        color: getThemeValue(this.theme).titleColor,
        backgroundColor: this.theme === 'chalk' ? '#222733' : '#fff'
      }
    },
    ...mapState(['theme'])
  },
  methods: {
    // 1.初始化echartsInstance对象
    initChart () {
      this.chartInstance = this.$echarts.init(this.$refs.trend_ref, this.theme)
      const initOption = {
        grid: {
          left: '3%',
          right: '3%',
          top: '35%',
          bottom: '6%',
          containLabel: true
        },
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          left: 20,
          top: '15%',
          icon: 'circle'
        },
        xAxis: {
          type: 'category',
          boundaryGap: false
        },
        yAxis: {
          type: 'value'
        }
      }
      this.chartInstance.setOption(initOption)
    },

    // 2.获取服务器端数据
    getData (res) {
      // // 获取trend数据 /api/trend
      // const { data: res } = await this.$http.get('trend')
      // socket res - 服务端发送给客户端的图表数据
      this.allData = res
      this.currentTitle = this.allData.type[0].text
      this.currentKey = this.allData.type[0].key
      this.updateChart()
    },

    // 3.更新图表
    updateChart () {
      // 半透明的颜色值
      const colorArr1 = [
        'rgba(11, 168, 44, 0.5)',
        'rgba(44, 110, 255, 0.5)',
        'rgba(22, 242, 217, 0.5)',
        'rgba(254, 33, 30, 0.5)',
        'rgba(250, 105, 0, 0.5)'
      ]
      // 全透明的颜色值
      const colorArr2 = [
        'rgba(11, 168, 44, 0)',
        'rgba(44, 110, 255, 0)',
        'rgba(22, 242, 217, 0)',
        'rgba(254, 33, 30, 0)',
        'rgba(250, 105, 0, 0)'
      ]
      // 处理数据
      // 类目轴的数据
      const timeArr = this.allData.common.month
      // Y轴的数据
      const valueArr = this.allData[this.currentKey].data
      // series数据
      const seriesArr = valueArr.map((item, index) => {
        return {
          name: item.name,
          type: 'line',
          data: item.data,
          stack: this.currentKey,
          areaStyle: {
            color: new this.$echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { // 0%时的颜色值
                offset: 0,
                color: colorArr1[index]
              },
              { // 100%时的颜色值
                offset: 1,
                color: colorArr2[index]
              }
            ])
          }
        }
      })
      // 图例数据
      const legendArr = valueArr.map(item => {
        return item.name
      })
      // 数据配置项
      const dataOption = {
        legend: {
          data: legendArr
        },
        xAxis: {
          data: timeArr
        },
        series: seriesArr
      }
      this.chartInstance.setOption(dataOption)
    },

    // 4.分辨率适配
    resizeChart () {
      const titleFontSize = this.$refs.trend_ref.offsetWidth / 100 * 3.6
      this.titleFontSize = titleFontSize
      const resizeOption = {
        legend: {
          textStyle: {
            fontSize: titleFontSize
          },
          itemWidth: titleFontSize,
          itemHeight: titleFontSize,
          itemGap: titleFontSize
        }
      }
      this.chartInstance.setOption(resizeOption)
      this.chartInstance.resize()
    },

    // 5.选择类别
    choiceTitleType (currentKey) {
      this.currentKey = currentKey
      this.updateChart()
      this.showChoice = false
    }
  },
  watch: {
    theme () {
      console.log('主题切换了')
      // 1.销毁当前图表
      this.chartInstance.dispose()
      // 2.重新注册当前图表 -- 以最新主题渲染图表
      this.initChart()
      this.resizeChart()
      this.updateChart()
    }
  }
}
</script>

<style lang="less" scoped>
.title{
  position: absolute;
  top: 20px;
  left: 20px;
  z-index: 10;
  .title-icon{
    margin-left: 20px;
    cursor: pointer;
  }
  .select-con{
    margin-left: 20px;
    .select-item{
      cursor: pointer;
    }
  }
}
</style>
